package com.newland.zxy;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2021/1/15
 */
public class Main implements Watcher {

    //数据增删改查参考测试文件夹

    private static CountDownLatch countDownLatch=new CountDownLatch(1);
    private static ZooKeeper zooKeeper;
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zooKeeper = new ZooKeeper("127.0.0.1:2181",5000,new Main());
        ZooKeeper.States state = zooKeeper.getState();
        System.out.println(state);
        countDownLatch.await();
        System.out.println("连接");
        System.out.println(zooKeeper.getState());
//        zooKeeper.create("/zxy","ccc".getBytes("utf-8"),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
        zooKeeper.getChildren("/zxy",true);
        //监听子节点需反复注册
        for(int i=0;i<20;i++)
        {
            zooKeeper.create("/zxy/zzz","dd".getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
            Thread.sleep(2000);
        }
    }

    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState()== Event.KeeperState.SyncConnected)
        {
            countDownLatch.countDown();
        }

        if(watchedEvent.getType()==Event.EventType.NodeChildrenChanged)
        {
            try {
                //监听子节点需反复注册
                List<String> children = zooKeeper.getChildren(watchedEvent.getPath(), true);
                System.out.println(children);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
